/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.passwords;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.json.JSONObject;
import org.webos.java.base.Frame;
import org.webos.java.base.FrameType;
import org.webos.java.base.NetworkManager;
import org.webos.java.base.RemoteMessage;
import org.webos.java.base.SystemManager;
import org.webos.java.base.dialog.QuestionDialog;
import org.webos.java.base.dialog.QuestionResponse;
import org.webos.java.base.grid.GridControllerItem;
import org.webos.java.base.tree.TreeController;
import org.webos.java.base.tree.TreeControllerItem;
import org.webos.java.base.tree.TreeSelectionListener;
import org.webos.java.base.workspace.Workspace;
import org.webos.java.root.Log;



/**
 *
 * @author kostya
 */

class CategorieItem extends TreeControllerItem<String, CategorieItem>{

    int id = 0;
    String name = "";

    public CategorieItem(TreeController aController, int aID, String aName) {
        super(aController, aName);
        setType(TreeControllerItem.TYPE_LEAF);
        setId(Integer.toString(aID));
        id = aID;
        name = aName;
    }

    @Override
    public void objectTOJSON(JSONObject aObject) {
        aObject.putOpt("name", name);
        aObject.putOpt("icon_cls", "passwords_icns passwords_icn_folder");
    }

}

@FrameType(code="tree", jsClass="passwords.Categories")
public class CategoriesFrame extends Frame<PasswordManager>{

    TreeController<CategorieItem> controller = new TreeController<CategorieItem>(this);

    public CategoriesFrame(PasswordManager aPasswordManager, Workspace aWorkspace) {
        super(aPasswordManager, aWorkspace);
        controller.getRoot().setComparator(new CatComparator());
        setTitle("Folders:");
        setIcon("passwords_icns passwords_icn_folders");
        controller.addTreeSelectionListener(new TreeSelectionListener() {

            public void selectionChanged(TreeControllerItem aItem) {
                //Test
                getApplication().grid.displayPasswords(aItem==null?null:(CategorieItem) aItem);
            }
        });
        reloadList();
        if(controller.getChildrenCount()>0){
            TreeControllerItem item = controller.findItemByID(getApplication().getOptionObject("options").optString("folder", ""));
            controller.setSelectedItem(item!=null?item:controller.getChild(0), false);
        }
    }

    @RemoteMessage
    public void newFolder(JSONObject aData){
        new AddNewCategorie(getApplication(), true, "", 0);
    }

    @RemoteMessage
    public void removeFolder(JSONObject aData){
        final CategorieItem item = (CategorieItem) controller.getSelected();
        if(item!=null){
            int aResponse = new QuestionDialog(getApplication(), "aRe you sure want to remove folder '"+
                    SystemManager.prepareTextForView(item.name, true)+"'?").ask();
            if(aResponse==0){
                //Remove here
                Log.debug(this, "Removing item "+item.name);
                try {
                    PreparedStatement st = getApplication().connection.prepareQuery("delete from PASSWORDS where id_cat=?");
                    st.setInt(1, item.id);
                    st.execute();
                    st.close();
                    st = getApplication().connection.prepareQuery("delete from CATEGORIES where id=?");
                    st.setInt(1, item.id);
                    st.execute();
                    st.close();
                    getApplication().connection.commit();
                    item.remove();
                } catch (Throwable t) {
                    getApplication().connection.rollback();
                    Log.error(this, "Exception thrown: " + t.getMessage());
                    t.printStackTrace();
                    getApplication().sendError(1004, "Can't delete folder '"+item.name+"'");
                }
            }
        }
    }

    @RemoteMessage
    public void editFolder(JSONObject aData){
        CategorieItem sel = (CategorieItem) controller.getSelected();
        if(sel!=null)
            new AddNewCategorie(getApplication(), false, sel.name, sel.id);
    }

    @RemoteMessage
    public JSONObject movePassword(JSONObject aData){
        CategorieItem sel = (CategorieItem) controller.getSelected();
        try {
            int passwordID = aData.optInt("password", 0);
            int catID = aData.optInt("folder", 0);
            if(sel!=null && sel.id!=catID){
                PreparedStatement st = getApplication().connection.prepareQuery(
                        "update PASSWORDS set id_cat=? where id=?");
                st.setInt(1, catID);
                st.setInt(2, passwordID);
                st.execute();
                getApplication().connection.commit();
                PasswordItem itm = getApplication().grid.controller.getItem(Integer.toString(passwordID));
                if(itm!=null)
                    getApplication().grid.controller.removeItem(itm);
            }
            return null;
        } catch (Throwable t) {
            getApplication().connection.rollback();
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return NetworkManager.getErrorObject(1015, "Can't move item");
    }

    boolean createOrEditCategorie(boolean aNewCategorie, int aID, String aName){
        try {
            PreparedStatement st = null;
            if(aNewCategorie){
                st = getApplication().connection.prepareQuery("insert into categories " +
                        "(name) values (?)");
                st.setString(1, aName);
            }else{
                st = getApplication().connection.prepareQuery("update categories set " +
                        "name=? where id=?");
                st.setString(1, aName);
                st.setInt(2, aID);
            }
            st.execute();
            st.close();
            getApplication().connection.commit();
            if(aNewCategorie){
                CategorieItem item = new CategorieItem(controller, getApplication().connection.getLastID(), aName);
                Log.debug(this, "Added new item "+item.id);
                controller.getRoot().appendChild(item);
                controller.setSelectedItem(item);
            }else{
                CategorieItem item = (CategorieItem) controller.getSelected();
                if(item!=null){
                    item.name = aName;
                    item.notifyModified();
                    controller.setSelectedItem(item);
                }
            }
            return true;
        } catch (Throwable t) {
            getApplication().connection.rollback();
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return false;
    }

    void reloadList(){
        controller.setSilentMode();
        controller.getRoot().clear();
        try {
            PreparedStatement st = getApplication().connection.
                    prepareQuery("select id, name from categories");
            ResultSet rset = st.executeQuery();
            while(rset.next()){
                controller.getRoot().appendChild(new CategorieItem(controller, rset.getInt(1), rset.getString(2)));
            }
            st.close();
//            Log.debug(this, "Folders size = "+controller.getRoot().getChildrenCount());
            controller.sendTree();
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
    }

}
